package com.sky.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import cn.mybatis.mp.core.sql.executor.chain.QueryChain;
import cn.mybatis.mp.core.mybatis.mapper.context.Pager;
import com.sky.constant.MessageConstant;
import com.sky.vo.UserCollectionVO;
import com.sky.entity.Books;
import com.sky.entity.Usercollections;
import com.sky.exception.BaseException;
import com.sky.mapper.BooksMapper;
import com.sky.mapper.UsercollectionsMapper;
import com.sky.service.UsercollectionsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author majun
 * @package com.sky.service.impl
 * @date 2025/1/1 15:28
 */
@Service
@Slf4j
public class UsercollectionsServiceImpl implements UsercollectionsService {

    @Autowired
    private UsercollectionsMapper usercollectionsMapper;

    @Autowired
    private BooksMapper booksMapper;

    /**
     * 检查图书是否已收藏
     *
     * @param bookId 图书ID
     * @return "1" 表示已收藏，"0" 表示未收藏
     */
    @Override
    public String getBookCheckIsFavorite(Integer bookId) {
        if (bookId == null) {
            throw new BaseException(MessageConstant.THE_SUBMISSION_CANNOT_BE_EMPTY);
        }

        try {
            // 获取当前登录用户ID
            Integer userId = StpUtil.getLoginIdAsInt();

            // 查询用户收藏记录
            Usercollections collection = QueryChain.of(usercollectionsMapper)
                    .eq(Usercollections::getUserId, userId)
                    .eq(Usercollections::getBookId, bookId)
                    .get();

            // 如果找到收藏记录，返回"1"，否则返回"0"
            return collection != null ? "1" : "0";

        } catch (Exception e) {
            log.error("检查图书收藏状态失败 - 图书ID: {}", bookId, e);
            return "false";  // 发生错误时默认返回未收藏
        }
    }

    /**
     * 添加收藏
     *
     * @param userId 用户ID
     * @param bookId 图书ID
     */
    @Override
    @Transactional
    public void addFavorite(Integer userId, Integer bookId) {
        // 1. 检查图书是否存在
        Books book = booksMapper.get(where -> where.eq(Books::getBookId, bookId));
        if (book == null) {
            throw new BaseException(MessageConstant.BOOK_NOT_FOUND);
        }

        // 2. 检查是否已经收藏
        Usercollections existingCollection = QueryChain.of(usercollectionsMapper)
                .eq(Usercollections::getUserId, userId)
                .eq(Usercollections::getBookId, bookId)
                .get();

        if (existingCollection != null) {
            throw new BaseException(MessageConstant.BOOK_ALREADY_COLLECTED);
        }

        // 3. 添加收藏记录
        Usercollections collection = new Usercollections();
        collection.setUserId(userId);
        collection.setBookId(bookId);
        collection.setCollectionTime(new Date());

        usercollectionsMapper.save(collection);

        log.info("用户 {} 收藏图书 {} 成功", userId, bookId);
    }

    /**
     * 取消收藏
     *
     * @param userId 用户ID
     * @param bookId 图书ID
     */
    @Override
    @Transactional
    public void cancelFavorite(Integer userId, Integer bookId) {
        // 1. 检查图书是否存在
        Books book = booksMapper.get(where -> where.eq(Books::getBookId, bookId));
        if (book == null) {
            throw new BaseException(MessageConstant.BOOK_NOT_FOUND);
        }

        // 2. 检查是否已经收藏
        Usercollections existingCollection = QueryChain.of(usercollectionsMapper)
                .eq(Usercollections::getUserId, userId)
                .eq(Usercollections::getBookId, bookId)
                .get();

        if (existingCollection == null) {
            throw new BaseException(MessageConstant.COLLECTION_NOT_FOUND);
        }

        // 3. 删除收藏记录
        usercollectionsMapper.delete(where -> {
            where.eq(Usercollections::getUserId, userId)
                    .eq(Usercollections::getBookId, bookId);
        });

        log.info("用户 {} 取消收藏图书 {} 成功", userId, bookId);
    }

    /**
     * 获取图书的收藏数量
     *
     * @param bookId 图书ID
     * @return 收藏数量
     */
    @Override
    public Long getCollectionCount(Integer bookId) {
        return (long) QueryChain.of(usercollectionsMapper)
                .eq(Usercollections::getBookId, bookId)
                .count();
    }

    /**
     * 批量获取图书的收藏数量
     *
     * @param bookIds 图书ID列表
     * @return 图书ID和收藏数量的映射
     */
    @Override
    public Map<Integer, Long> getCollectionCounts(List<Integer> bookIds) {
        if (bookIds == null || bookIds.isEmpty()) {
            return Map.of();  // 如果ID列表为空，返回空Map
        }

        Map<Integer, Long> result = new HashMap<>();
        for (Integer bookId : bookIds) {
            Long count = getCollectionCount(bookId);
            result.put(bookId, count);
        }
        return result;
    }

    /**
     * 分页获取用户收藏列表
     * 实现步骤：
     * 1. 先查询用户收藏记录表获取分页数据
     * 2. 遍历收藏记录，查询对应的图书详细信息
     * 3. 组装VO对象返回给前端
     *
     * @param userId 用户ID
     * @param page 当前页码，从1开始
     * @param pageSize 每页显示数量
     * @return 包含图书详细信息的收藏列表分页数据
     */
    @Override
    public Pager<UserCollectionVO> getUserCollectionsByPage(Integer userId, Integer page, Integer pageSize) {
        // 1. 创建分页对象并查询收藏记录
        Pager<Usercollections> collectionPager = QueryChain.of(usercollectionsMapper)
                .eq(Usercollections::getUserId, userId)
                .orderByDesc(Usercollections::getCollectionTime)
                .paging(Pager.of(page,pageSize));

        // 2. 创建返回的VO分页对象
        Pager<UserCollectionVO> voPager = new Pager<>(page, pageSize);
        voPager.setTotal(collectionPager.getTotal());
        voPager.setNumber(collectionPager.getNumber());

        // 3. 转换数据
        List<UserCollectionVO> voList = new ArrayList<>();
        if (collectionPager.getResults() != null && !collectionPager.getResults().isEmpty()) {
            for (Usercollections collection : collectionPager.getResults()) {
                // 查询对应的图书信息
                Books book = booksMapper.get(where -> where.eq(Books::getBookId, collection.getBookId()));
                if (book != null) {
                    UserCollectionVO vo = new UserCollectionVO();
                    // 设置收藏信息
                    vo.setCollectionId(collection.getCollectionId());
                    vo.setBookId(collection.getBookId());
                    vo.setCollectionTime(collection.getCollectionTime());
                    
                    // 设置图书信息
                    vo.setTitle(book.getTitle());
                    vo.setAuthor(book.getAuthor());
                    vo.setPublishDate(book.getPublishDate());
                    vo.setStockQuantity(book.getStockQuantity());
                    vo.setDescription(book.getDescription());
                    vo.setCoverImage(book.getCoverImage());
                    vo.setPopularityScore(book.getPopularityScore());
                    vo.setWordCount(book.getWordCount());
                    
                    voList.add(vo);
                }
            }
        }
        voPager.setResults(voList);
        
        return voPager;
    }

}
